<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设备管理</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- 引入Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-4">
    <h1 class="mb-4">设备管理</h1>
    <!-- 新增设备按钮 -->
    <button type="button" class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#equipmentModal" onclick="openModal('add')">新增设备</button>

    <!-- 模态框 -->
    <div class="modal fade" id="equipmentModal" tabindex="-1" aria-labelledby="equipmentModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="equipmentModalLabel">设备信息</h5>
                    <button type="button" class="btn-close" data-bs-close="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="equipmentForm">
                        <div class="mb-3">
                            <label for="name" class="form-label">设备名称:</label>
                            <input type="text" class="form-control" id="name" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="ip" class="form-label">设备IP:</label>
                            <input type="text" class="form-control" id="ip" name="ip" list="ipList" required>
                            <datalist id="ipList">
                                <!-- IP 列表将动态插入到这里 -->
                            </datalist>
                        </div>
                        <div class="mb-3">
                            <label for="username" class="form-label">用户名:</label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">密码:</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <div class="mb-3">
                            <label for="type" class="form-label">设备类型:</label>
                            <input type="text" class="form-control" id="type" name="type" required>
                        </div>
                        <div class="mb-3">
                            <label for="remark" class="form-label">备注:</label>
                            <input type="text" class="form-control" id="remark" name="remark">
                        </div>
                        <div class="mb-3">
                            <label for="status" class="form-label">状态:</label>
                            <input type="text" class="form-control" id="status" name="status" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="saveButton" onclick="saveEquipment()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <h2 class="mb-3">设备列表</h2>
    <table id="equipmentTable" class="table table-striped table-bordered">
        <thead class="table-dark">
            <tr>
                <th>设备名称</th>
                <th>设备IP</th>
                <th>用户名</th>
                <th>密码</th>
                <th>设备类型</th>
                <th>备注</th>
                <th>状态</th>
                <th>总访问人次</th>
                <th>今日访问人次</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <!-- 设备列表将动态插入到这里 -->
        </tbody>
    </table>

    <!-- 访问记录模态框 -->
    <div class="modal fade" id="accessRecordsModal" tabindex="-1" aria-labelledby="accessRecordsModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="accessRecordsModalLabel">访问记录</h5>
                    <button type="button" class="btn-close" data-bs-close="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <table id="accessRecordsTable" class="table table-striped table-bordered">
                        <thead class="table-dark">
                            <tr>
                                <th>游客姓名</th>
                                <th>游客身份证</th>
                                <th>访问时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 访问记录将动态插入到这里 -->
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        function loadEquipments() {
            axios.get('/equipments')
                .then(response => {
                    const tbody = document.querySelector('#equipmentTable tbody');
                    tbody.innerHTML = '';
                    response.data.forEach(equipment => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${equipment.name}</td>
                            <td>${equipment.ip}</td>
                            <td>${equipment.username}</td>
                            <td>${equipment.password}</td>
                            <td>${equipment.type}</td>
                            <td>${equipment.remark}</td>
                            <td>${equipment.status}</td>
                            <td>${equipment.totalVisits}</td>
                            <td>${equipment.todayVisits}</td>
                            <td>
                                <button onclick="editEquipment('${equipment.ip}')">编辑</button>
                                <button onclick="deleteEquipment('${equipment.ip}')">删除</button>
                                <button onclick="viewAccessRecords('${equipment.ip}')">查看访问记录</button>
                            </td>
                        `;
                        tbody.appendChild(row);
                    });
                })
                .catch(error => console.error('加载设备列表失败:', error));
        }

        function loadDeviceIps() {
            axios.get('/devices/scan')
                .then(response => {
                    const ipList = document.querySelector('#ipList');
                    ipList.innerHTML = '';
                    response.data.forEach(ip => {
                        const option = document.createElement('option');
                        option.value = ip;
                        ipList.appendChild(option);
                    });
                })
                .catch(error => console.error('加载设备IP列表失败:', error));
        }

        function openModal(action, ip) {
            const saveButton = document.getElementById('saveButton');
            if (action === 'add') {
                document.getElementById('equipmentForm').reset();
                loadDeviceIps(); // 确保在打开模态框时加载设备IP列表
                saveButton.setAttribute('onclick', 'addEquipment()');
            } else if (action === 'edit' && ip) {
                editEquipment(ip);
                saveButton.setAttribute('onclick', 'updateEquipment()');
            }
        }

        function saveEquipment() {
            const saveButton = document.getElementById('saveButton');
            if (saveButton.getAttribute('onclick') === 'addEquipment()') {
                addEquipment();
            } else if (saveButton.getAttribute('onclick') === 'updateEquipment()') {
                updateEquipment();
            }
        }

        function addEquipment() {
            const form = document.getElementById('equipmentForm');
            const equipment = {
                name: form.name.value,
                ip: form.ip.value,
                username: form.username.value,
                password: form.password.value,
                type: form.type.value,
                remark: form.remark.value,
                status: form.status.value
            };
            axios.post('/equipments', equipment)
                .then(() => {
                    loadEquipments();
                    bootstrap.Modal.getInstance(document.getElementById('equipmentModal')).hide();
                })
                .catch(error => console.error('添加设备失败:', error));
        }

        function editEquipment(ip) {
            axios.get(`/equipments/${ip}`)
                .then(response => {
                    const equipment = response.data;
                    const form = document.getElementById('equipmentForm');
                    form.name.value = equipment.name;
                    form.ip.value = equipment.ip;
                    form.username.value = equipment.username;
                    form.password.value = equipment.password;
                    form.type.value = equipment.type;
                    form.remark.value = equipment.remark;
                    form.status.value = equipment.status;
                    const modal = new bootstrap.Modal(document.getElementById('equipmentModal'));
                    modal.show();
                })
                .catch(error => console.error('获取设备信息失败:', error));
        }

        function updateEquipment() {
            const form = document.getElementById('equipmentForm');
            const equipment = {
                name: form.name.value,
                ip: form.ip.value,
                username: form.username.value,
                password: form.password.value,
                type: form.type.value,
                remark: form.remark.value,
                status: form.status.value
            };
            axios.put('/equipments', equipment)
                .then(() => {
                    loadEquipments();
                    bootstrap.Modal.getInstance(document.getElementById('equipmentModal')).hide();
                })
                .catch(error => console.error('更新设备失败:', error));
        }

        function deleteEquipment(ip) {
            if (confirm('确定要删除该设备吗？')) {
                axios.delete(`/equipments/${ip}`)
                    .then(() => {
                        alert('设备删除成功');
                        loadEquipments();
                    })
                    .catch(error => console.error('删除设备失败:', error));
            }
        }

        function viewAccessRecords(ip) {
            axios.get(`/visitor-device-records/device/${ip}`)
                .then(response => {
                    const tbody = document.querySelector('#accessRecordsTable tbody');
                    tbody.innerHTML = '';
                    // 过滤当天的访问记录并按访问时间倒序排序
                    const today = new Date().toISOString().split('T')[0];
                    const todayRecords = response.data.filter(record => record.accessTime.startsWith(today))
                        .sort((a, b) => new Date(b.accessTime) - new Date(a.accessTime));
                    todayRecords.forEach(record => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${record.visitorName}</td>
                            <td>${record.visitorIdCard}</td>
                            <td>${new Date(record.accessTime).toLocaleString()}</td>
                        `;
                        tbody.appendChild(row);
                    });
                    // 显示模态框
                    const modal = new bootstrap.Modal(document.getElementById('accessRecordsModal'));
                    modal.show();
                })
                .catch(error => console.error('加载访问记录失败:', error));
        }

        // 页面加载时加载设备列表
        window.onload = loadEquipments;
    </script>
    <!-- 引入Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>